
class Structure < Controller

  def menu e
    if parent_node_id = e.params['subnode']
      form = Node::ShortForm.new()
      form.env = e.env
      form.fill 'parent_node_id' => parent_node_id

      if e.request.post?
        form.handle e.params
      end
    end


    NodeMenu.each { |n, li|
      li.append_child Element.new(:a, n.title, :href => link('edit/'+n.id.to_s))
      if id = e.env[:unprocessed_tail].first == n.id.to_s
        if e.params['subnode'] == n.id.to_s
          li.append_child form
        else
          li.append_child Element.new(
            :a, '+ add',
            :href => '?subnode='+n.id.to_s,
            :class => 'button'
          )
        end
      end
    }.to_s
  end

  def index e
    s = ''

    s << menu(e)

    if !Node.first(:is_root => true)
      s << Element.new(:a, 'přidej hlavní stránku', :href => link('add')).to_s
    end

    if node_id = e.params['edit']
      form = Node::ShortForm.new()
      form.env = e.env
      if node = Node.get(node_id.to_i)
        attrs = node.attributes
        if node.parent_node
          attrs.merge!('parent_node_id' => node.parent_node.id)
        end
        form.fill attrs
      end

      if e.request.post?
        form.handle e.params
      end
    end

    if delete = e.params['delete']
      Node.get(delete).destroy
    end

    s
  end


  def add e
    s = '<h1>Přidat uzel</h1>'
    s << menu(e)

    form = Node::AdminForm.new()
    form.env = e.env

    if e.request.post?
      form.handle e.params
    end

    s << form.to_s
    s
  end
  

  def edit e
    s = ''

    id = e.env[:unprocessed_tail].first.to_i
    if id != @page.id
      @page = Node.get(id)
    end

    form = Node::AdminForm.new()
    form.fill @page.attributes

    if e.params['save-node'] || e.params['delete-node']
      form.handle e.params
    end

    s << menu(e)    
    s << form.to_s
    s << @page.content.creator_form(e)
    s
  end




  class Layout
    def self.render content
      <<HTML
<div class="structure-editor">
  #{content}
</div>
HTML
    end
  end

  layout Layout

end
